package com.anlgin.anl_tea.controller;

import com.anlgin.anl_tea.entities.Address;
import com.anlgin.anl_tea.entities.RetResponse;
import com.anlgin.anl_tea.entities.RetResult;
import com.anlgin.anl_tea.entities.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.anlgin.anl_tea.service.ILoginService;
import com.anlgin.anl_tea.tools.CommodityTools;

import java.util.List;

/**
 * 用户端接口
 */
@RestController
@CrossOrigin
public class LoginController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ILoginService loginService;

    @Autowired
    private CommodityTools tools;

    @PostMapping("/login")
    public RetResult login(User user, String tel, String eMail) {
        logger.info("用户登录"+user.toString());
        User loginUser = new User();
        Integer mode = 0;
        if (user.getTel() != null) {
//            获取手机号码登录
            loginUser = loginService.findUserByTel(user);
        } else if (user.getEMail() != null) {
//            获取邮箱登录
            mode = 1;
            loginUser = loginService.findUserByEmail(user);
        }
        if (loginUser == null) {
//            未获得账号，进行注册
            String uuid = tools.getUUID();
            user.setUserId(uuid);
            user.setIntegral(0);
            if (mode == 0) {
                String userName = "tea"+tools.getCurrentDate()+user.getTel();
                user.setUsername(userName.replace(" ", ""));
            } else {
                String userName = "tea"+tools.getCurrentDate()+user.getEMail();
                user.setUsername(userName.replace(" ", ""));
            }
            loginService.InsertUser(user);
            loginUser = user;
        }
        logger.info("获取登录的账号信息"+loginUser.toString());
        return RetResponse.makeOKRsp(loginUser);
    }

    @PostMapping("/getAddressList")
    public RetResult getAddressList(User user) {
        logger.info("用户查询地址列表"+user.toString());
        List<Address> arrayList = loginService.getAddressList(user);
        return RetResponse.makeOKRsp(arrayList);
    }

    @PostMapping("/insertAddress")
    public RetResult InsertAddress(Address address) {
        if (address.getIsDefault() == 1) {
            User user = new User();
            user.setUserId(address.getUserId());
            loginService.cancelDefault(user);
        }
        logger.info("用户添加地址"+address.getUserId());
        loginService.insertAddress(address);
        return RetResponse.makeOKRsp();
    }

    @PostMapping("/updateUser")
    public RetResult updateUser(User user) {
        loginService.updateUser(user);
        return RetResponse.makeOKRsp();
    }

}
